package controllers

import (
	"bytes"
	"encoding/binary"
	"encoding/hex"
	"ktvserver/core/session"
	"log"
)

// 在线页面
type OnlineController struct {
	UserController
}

const (
	PAGE_SIZE = 100
)

func (c *OnlineController) Get() {
	c.TplNames = "online"
	c.Data["title"] = "在线用户"

	total_count := session.GetSessionsCount()
	cur_offset, err := c.GetInt(":offset")
	if err != nil {
		cur_offset = 0
	}

	if cur_offset < 0 || cur_offset >= total_count {
		cur_offset = 0
	}

	next_offset := cur_offset + PAGE_SIZE
	pre_offset := cur_offset - PAGE_SIZE

	if pre_offset < 0 || pre_offset >= total_count {
		pre_offset = 0
	}

	if next_offset >= total_count {
		next_offset = cur_offset
	}

	sessions := session.GetSessionsList(cur_offset, PAGE_SIZE)

	c.Data["sessions"] = sessions
	c.Data["total"] = session.GetSessionsCount()

	// 分页设置
	c.Data["pre_offset"] = pre_offset
	c.Data["next_offset"] = next_offset
	c.Data["cur_offset"] = cur_offset

	if len(sessions) == 0 {
		c.Data["noonlineuser"] = 1
	}
}

// 在线页面
type OnlineContentController struct {
	UserController
}

func (c *OnlineContentController) Get() {
	c.TplNames = "onlineContent"
	c.Data["title"] = "在线用户"

	total_count := session.GetSessionsCount()
	cur_offset, err := c.GetInt(":offset")
	if err != nil {
		cur_offset = 0
	}

	if cur_offset < 0 || cur_offset >= total_count {
		cur_offset = 0
	}

	next_offset := cur_offset + PAGE_SIZE
	pre_offset := cur_offset - PAGE_SIZE

	if pre_offset < 0 || pre_offset >= total_count {
		pre_offset = 0
	}

	if next_offset >= total_count {
		next_offset = cur_offset
	}

	sessions := session.GetSessionsList(cur_offset, PAGE_SIZE)

	c.Data["sessions"] = sessions
	c.Data["total"] = session.GetSessionsCount()

	// 分页设置
	c.Data["pre_offset"] = pre_offset
	c.Data["next_offset"] = next_offset
	c.Data["cur_offset"] = cur_offset

	if len(sessions) == 0 {
		c.Data["noonlineuser"] = 1
	}

}

// 下载用户详细信息
type DetailController struct {
	UserController
}

// 详细页面
func (c *DetailController) Get() {
	c.TplNames = "detail"
	c.Data["title"] = "详细信息"

	// 转换令牌
	tokenStr := c.Ctx.Input.Param(":token")
	if len(tokenStr) != 16 {
		c.Redirect("/ktv/online", 302)
		return
	}

	// 转换为二进制数据
	tokenBytes, err := hex.DecodeString(tokenStr)
	if err != nil || len(tokenBytes) != 8 {
		c.Redirect("/ktv/online", 302)
		return
	}

	var token uint64
	rd := bytes.NewReader(tokenBytes)
	binary.Read(rd, binary.BigEndian, &token)

	// 检查session值是否存在
	sess := session.GetSession(token)
	if sess == nil {
		log.Printf("sess3, token not found token=%x", token)
		c.Redirect("/ktv/online", 302)
		return
	}

	c.Data["sess"] = sess
	c.Data["downloadcount"] = len(sess.GetDownloadRecord())

}
